package com.htc.callcare.services;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.android.internal.telephony.ITelephony;
import com.htc.callcare.datacontroller.VoiMailFileController;
import com.htc.callcare.infrastructure.globalVar;
import com.htc.callcare.viewcontroller.Popup_Call;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

public class CallReceiver extends BroadcastReceiver {
	Context mContext;
	Intent intent;
	static String phoneNumber;
	static int type = -1;
	static boolean popUpCallShow = false;
	static Popup_Call popup_Call;
	public static VoiMailFileController voiceMailFileController;
	//Flag to allow record voice mail
	static boolean voiceMail = false;
	static boolean voiceMailisRecording = false;
	static boolean istop = false;
	public static boolean isRecording;
	//public static MediaRecorder recorder;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub

		this.mContext = context;
		voiceMailFileController = new VoiMailFileController(mContext);
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String temp = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
		if (temp != null && !temp.equals("")) {
			phoneNumber = temp;
			Toast.makeText(context, phoneNumber, Toast.LENGTH_SHORT).show();
		}

		PhoneCallStateListener customPhoneListener = new PhoneCallStateListener(
				context);
		telephonyManager.listen(customPhoneListener,
				PhoneStateListener.LISTEN_CALL_STATE);
	}

	public class PhoneCallStateListener extends PhoneStateListener {

		
		
		Context context;

		public PhoneCallStateListener(Context context) {
			this.context = context;
		}

		/* (non-Javadoc)
		 * @see android.telephony.PhoneStateListener#onCallStateChanged(int, java.lang.String)
		 */
		public void onCallStateChanged(int state, String incomingNumber) {
			if(incomingNumber!=null&&!incomingNumber.equals("")){
				phoneNumber = incomingNumber;
			}
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				Log.e("thuutai", "CALL_STATE_IDLE");
				//voiceMailFileController.voiceMailEndRecord(voiceMail, isRecording);
				//endRecord(voiceMail, voiceMailisRecording);
				Log.e("thuutai", "end");
				voiceMail = false;
				voiceMailisRecording= false;
				try {
					if (popUpCallShow) {
						popup_Call.endrecord();
						wm.removeView(popup_Call);
						popup_Call = null;
						popUpCallShow = false;

					}
				} catch (IllegalArgumentException e) {
					Log.e(globalVar.logTab, e.toString());
				}
				
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				// -- check international call or not.
				Log.e("thuutai", "CALL_STATE_RINGING");
				phoneNumber = incomingNumber;

				ITelephony telephonyService = voiceMailFileController
						.getTelephonyService();

				if (!popUpCallShow) {
					showPopUp(1, phoneNumber);
				}
				
				//catch the phone
			/*	if(phoneNumber.equals("0996586134")){
				try {
					telephonyService.answerRingingCall();
					Log.e("thuutai", "ringing1");
					voiceMail = true;
				} catch (Exception e) {
					voiceMailFileController.annswerPhoneHeadsethook();
					voiceMail = true;
					Log.e("thuutai", "ringing2");
				}
				}*/
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				Log.e("thuutai", "CALL_STATE_OFFHOOK");
				if(incomingNumber!=null&&!incomingNumber.equals("")){
					phoneNumber = incomingNumber;
				}
				if (!popUpCallShow) {
					showPopUp(0, phoneNumber);
				}
				int count =1;
				Log.e("thuutai", ""+count++);
				if(voiceMail&&!voiceMailisRecording){
					/*Intent plugin1 = new Intent(Intent.ACTION_HEADSET_PLUG);
					plugin1.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
					plugin1.putExtra("state", 0);
					plugin1.putExtra("name", "Headset");
					context.sendOrderedBroadcast(plugin1,
							"android.permission.CALL_PRIVILEGED");*/
					//voiceMailFileController.startrecord(phoneNumber, voiceMail);
				//	startrecord(incomingNumber, voiceMail);
					voiceMailisRecording = true;
					Log.e("thuutai", "catch the phone");
				}
				break;
			}
		}

		/*private void endRecord(boolean voiceMail, boolean voiceMailisRecording) {

			try {
				if(!istop){
					recorder.stop();
					Log.e("thuutai", "Stop record");
					recorder.reset();
					recorder.release();
					istop = true;
					voiceMail = false;
					}
					
				//}
			} catch (IllegalStateException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			catch (NullPointerException e) {
				// TODO: handle exception
				e.printStackTrace();
		}


		}
*/
		/*private void startrecord(String incomeCall, boolean Voicemail) {
			String name = "_";
			if (recorder == null&&Voicemail) {
				recorder = new MediaRecorder();

				String path = globalVar.voiceMailDir;

				recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
				recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
				recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				// Variable.recorder.setAudioEncodingBitRate(320);
				Date date = new Date();
				DateFormat datef = new SimpleDateFormat(globalVar.FORMAT_DAY);
				name = "_" + Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + "h"
						+ Calendar.getInstance().get(Calendar.MINUTE) + "_"
						+ datef.format(date) + "_" + incomeCall + ".amr";

				name = "Voicemail" + name;

				path += name;
				recorder.setOutputFile(path);
				try {
					recorder.prepare();
					recorder.start();
					Log.e("thuutai", "Start record");
					istop = false;
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				AudioManager audioManager = (AudioManager) context
						.getSystemService("audio");
				audioManager
						.setStreamVolume(
								AudioManager.STREAM_VOICE_CALL,
								audioManager
										.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
								0);

				audioManager.setMicrophoneMute(true);
				// Log.e("debugg", "set mute");
			}

		
		}
		
		
		*/
	};

	static WindowManager wm;

	public void showPopUp(int type, String phoneNumber) {
		popUpCallShow = true;
		wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
		WindowManager.LayoutParams params = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT,
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
						| WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
				WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
				PixelFormat.TRANSLUCENT);
		// ???
		params.x = 250;
		params.height = LayoutParams.WRAP_CONTENT;
		params.width = LayoutParams.FILL_PARENT;
		params.format = PixelFormat.TRANSLUCENT;
		params.gravity = Gravity.TOP;
		popup_Call = new Popup_Call(mContext);
		popup_Call.setType(type);
		popup_Call.setPhoneNumber(phoneNumber);
		wm.addView(popup_Call, params);
	}

	public void removePopUp() {
		wm.removeView(popup_Call);
	}
	
	

}
